package com.huluobo.a2109mvpimdemo.chat;

import android.util.Log;

import com.huluobo.a2109mvpimdemo.base.BasePresenter;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LC on 2023/11/21.
 */
public class ChatPresenter extends BasePresenter<ChatContract.View> implements ChatContract.Presenter {

    //消息列表的数据源
    public List<EMMessage> messages = new ArrayList<>();

    private static final int PAGE_SIZE = 10;

    @Override
    public void sendMessage(String username, String content) {
        //创建一条消息,注意参数的位置
        EMMessage emMessage = EMMessage.createTextSendMessage(content, username);
        //设置消息的类型为单聊,默认也是单聊,可以不设置
        emMessage.setChatType(EMMessage.ChatType.Chat);
        //设置消息状态的回调,成功或者失败
        emMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                if (isAttach()) {
                    getView().onSendMessageSuccess();
                }
            }

            @Override
            public void onError(int code, String error) {
                if (isAttach()) {
                    getView().onSendMessageFailed(error);
                }
            }
        });

        //更新数据源中的消息
        messages.add(emMessage);
        if (isAttach()) {
            getView().onStartSendMessage();
        }
        //通过环信发送消息
        EMClient.getInstance().chatManager().sendMessage(emMessage);
        Log.i("TagA", "messages:" + messages.size());
    }

    @Override
    public void addMessage(String username, List<EMMessage> messages) {
        this.messages.addAll(messages);

        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username);
        conversation.markAllMessagesAsRead();
    }

    @Override
    public void loadMessage(String username) {
        EMConversation emConversation = EMClient.getInstance().chatManager().getConversation(username);
        if (emConversation!=null){
            emConversation.markAllMessagesAsRead();//标记历史消息为已读
            messages.addAll(emConversation.getAllMessages());//在消息列表中加入所有历史消息
            if (isAttach()) {
                getView().onMessageLoaded();
            }
        }

    }

    @Override
    public void loadMoreMessage(String username) {
        EMConversation emConversation = EMClient.getInstance().chatManager().getConversation(username);
        String startId = messages.get(0).getMsgId();//查询历史消息记录的起始位置,也就是当前聊天的第0位
        List<EMMessage> emMessages = emConversation.loadMoreMsgFromDB(startId, PAGE_SIZE);
        messages.addAll(0, emMessages);//加载历史聊天记录时,不能list的末尾添加,也就是不能直接addALl,需要从第0位开始添加
        if (isAttach()) {
            //使用emMessages的size,是为了保证数据库或者服务器中不足10条历史消息,需要返回具体的size
            getView().onMoreMessageLoaded(emMessages.size());
        }
    }
}
